<template>
  <div class="update-article">
    <el-form :model="articleForm" :rules="articleFormRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="articleForm.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="文章类型" prop="type">
        <el-select v-model="articleForm.type" placeholder="请选择类型">
          <el-option :label="item.name" :value="item.value" v-for="(item, index) in articleTypes" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="coverImg">
        <div v-if="!isUpdateCoverImg && articleForm.coverImg" class="cover-img" @click="updateCoverImg">
          <img :src="baseUrl + articleForm.coverImg" alt="">
        </div>
        <div class="upload-cover" v-else>
          <!--手动上传-->
          <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1"
                     :class="{'hide': hideUpload}" :on-change="handleUpload" style="height: 120px;">
            <i slot="default" class="el-icon-plus"  v-if="!coverImg"></i>
            <div slot="file" v-else>
              <img class="el-upload-list__item-thumbnail" :src="coverImg" alt="" />
              <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
            </div>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="文章简介" prop="intro">
        <el-input type="textarea" v-model="articleForm.intro" placeholder="请输入文章简介"></el-input>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <RichTextEditor v-model="articleForm.content"
                        :isClear="isClear"
                        @change="change"
                        :value="articleForm.content"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">更新文章</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import RichTextEditor from "./RichTextEditor";
import ArticleDetailCard from "./ArticleDetailCard";
import { baseUrl } from "../api";
export default {
  name: "UpdateArticleCard",
  components: {
    RichTextEditor,
    ArticleDetailCard
  },
  props: {
    articleForm: { type:Object, required: true }
  },
  data() {
    return {
      userInfo: {},  // 用户信息

      // 文章封面
      isUpdateCoverImg: false,  // 是否更新封面图片
      hideUpload: false,  // 是否隐藏上传框
      fileList: [],
      coverImg: '',

      isClear: false,  // 是否清除文章内容
      baseUrl: baseUrl,
      articleTypes: [],  // 文章类型
      articleFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        intro: [
          { required: true, message: '请输入文章简介', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'change' }
        ]
      },

      // 文章预览
      dialogVisible: false
    };
  },
  methods: {
    getArticleTypeList() {
      let token= this.userInfo.token;
      this.$http({
        url: '/admin/getTypeList',
        method: 'get',
        headers: {Authorization: token}
      }).then(response=>{
        let result= response.data;
        if(result.code===200) {
          let data= JSON.parse(result.data);
          this.articleTypes= data.data;
        } else {
          this.$message.warning('获取文章类型失败');
        }
      }).catch(e=>{
        this.$message.warning('获取文章类型失败');
      })
    },


    // 更新文章封面
    updateCoverImg() {
      this.$confirm('是否更新文章封面?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isUpdateCoverImg= true;
      }).catch(() => {});
    },
    // 文章封面上传，注意：此时并未上传至服务端
    handleUpload(file, fileList) {
      // console.log(file, fileList);
      this.fileList= fileList;

      // 预览上传的图片
      let URL= window.URL || window.webkitURL;
      this.coverImg = URL.createObjectURL(file.raw);
      this.hideUpload= true;
    },
    // 删除最新上传的文章封面
    handleRemove() {
      this.fileList.pop();
      this.coverImg= '';
      this.hideUpload= false;
    },

    // 富文本编辑器
    change(val) {
      // console.log('val',val)
    },

    // 文章更新
    submitForm(formName) {
      let _this= this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let token= _this.userInfo.token;
          let formData = new FormData();  // 首先创建FormData对象
          for(let key in _this.articleForm) {
            formData.append(key, _this.articleForm[key]);
          }
          if(_this.fileList.length) {
            formData.append('file', _this.fileList[0].raw);
          }
          this.$http({
            url: '/admin/updateArticleById',
            method: 'post',
            data: formData,
            headers: {Authorization: token}
          }).then(response=>{
            let result= response.data;
            if(result.code===200) {
              this.$message.success('更新文章成功');
              this.$emit('update', '更新文章成功');
            } else {
              this.$message.warning('更新文章失败');
            }
          }).catch(e=>{
            this.$message.warning('更新文章失败');
          })
        } else {
          return false;
        }
      });
    },
  },

  mounted() {
    let userInfo= window.sessionStorage.getItem('userInfo');
    this.userInfo= JSON.parse(userInfo);
    this.getArticleTypeList();
  }
}
</script>

<style scoped lang="less">
.update-article {
  .el-select {
    width: 100%;
  }


  .cover-img {
    width: 120px;
    height: 120px;
    cursor: pointer;
    img {
      border-radius: 4px;
      width: 100%;
      height: 100%;
    }
  }

  .upload-cover {
    height: 120px;
    //line-height: 120px;
    & > div {
      height: 100%;
    }

    .hide /deep/ .el-upload--picture-card {
      display: none;
    }

    /deep/ .el-upload, /deep/ .el-upload--picture-card {
      width: 120px;
      height: 120px;
      line-height: 120px;
    }
    .el-upload-list--picture-card {
      width: 120px;
      height: 120px;
      line-height: 120px;
    }
    .el-upload-list--picture-card .el-upload-list__item-thumbnail,
    /deep/ .el-upload-list--picture-card .el-upload-list__item,
    /deep/ .el-upload-list--picture-card .el-upload-list__item-actions {
      width: 120px;
      height: 120px;
      line-height: 120px;
    }
  }
}
</style>
